//
//  AppDelegate.m
//  安好
//
//  Created by 王振邦 on 14-10-21.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "AppDelegate.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import "RightViewController.h"
#import "MainViewController.h"
#import "LeftViewController.h"
#import "XHDrawerController.h"
#import "ConsultingChatViewController.h"
#import "UserManager.h"
#import "ConsultList.h"
#import "ChatContent.h"
#import "PeerList.h"
#import "MobClick.h"
#import "XGPush.h"
#import "LCStatusBarOverlay.h"
#import "FMDatabaseQueue.h"
#import <MAMapKit/MAMapKit.h>
#define UmengAppkey @"5386985056240b0a081bb4b2"  //安好appKey
#define APIKey @"c36674eca6a6cb5e40526f275ed4d241"
#import "SystemMessageCenter.h"
#import "RemindDrugManager.h"
#import "Reachability.h"
//用药提醒展示页面
#import "TakeDrugReminderViewController.h"
#import "ForgotViewController.h"


@implementation AppDelegate
-(void)applicationDidReceiveMemoryWarning:(UIApplication *)application{
SDWebImageManager *mgr = [SDWebImageManager sharedManager]; [mgr cancelAll];
    [mgr.imageCache clearMemory];
}
/**
 *  app的类方法
 *
 *  @return app的类方法
 */
+ (AppDelegate *)app
{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    
    
    //使用友盟统计
    [MobClick startWithAppkey:UmengAppkey reportPolicy:BATCH channelId:nil];
    [MobClick checkUpdate];   //自动更新检查, 如果需要自定义更新请使用下面的方法,需要接收一个(NSDictionary *)appInfo的参数
//    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    
    [MobClick setAppVersion:kceshiVersion];
    
    [MobClick setCrashReportEnabled:YES];
    
    [MobClick setLogEnabled:NO];
    
    [[UserManager shareInstance]deleteUserImage];


    
    
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]&&[kVersion isEqualToString:@"1.22"]){
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
        MyNSLog("第一次启动");
        [[UIApplication sharedApplication] cancelAllLocalNotifications];
        
    }else{
        
        MyNSLog("已经不是第一次启动了");
        
    }
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    
    [self ISChangeVersion];
    
    /**
     *  改变主视图的颜色
     *
     *  @param note 无
     *
     *  @return 无
     */
    [[NSNotificationCenter defaultCenter] addObserverForName:@"LeftAnimation" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note){
        self.leftView = YES;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"HiddenLeftUser" object:nil];

        [self viewShowWifiView];
        self.window.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"功能_背景视图"]];
    }];
    [[NSNotificationCenter defaultCenter] addObserverForName:@"GightAnimation" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note){
        self.leftView = NO;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ShowLeftUser" object:nil];

        self.window.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"功能_背景视图"]];
    }];
    [[NSNotificationCenter defaultCenter] addObserverForName:@"WeixinBack" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note){
        self.window.backgroundColor = [UIColor whiteColor];
    }];
//    [[NSNotificationCenter defaultCenter] addObserverForName:@"CONNECT_WEBSOCKDET" object:self queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
//        [self WBSocket];
//    }];
    /**
     *  新浪
     */
    [self loginSina];
    /**
     *  QQ
     */
    [self loginQQ];
    /**
     *  微信
     */
    [self WXAlloc];
    /**
     *  信鸽
     */
    [self XGAlloc];
    /**
     *  左视图
     */
    [self LeftAlloc];
    /**
     *  websocket
     */
    [self AHReach];
//    [self WBSocket];
    [self  MaMap];
    //初始化 window 消息
     [LCStatusBarOverlay shared];
    
//    [[NSNotificationCenter defaultCenter] addObserverForName:@"ARHwifi" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note){
//        [self viewShowWifiView];
//    }];
//    [[NSNotificationCenter defaultCenter] addObserverForName:@"ARH3G" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
//        [self viewShowWifiView];
//    }];
//    [[NSNotificationCenter defaultCenter] addObserverForName:@"ARHNOwifi" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
//        [self viewHiddenWifiView];
//        
//    }];
    
 
    [self.window makeKeyAndVisible];
    
    int stauts = [UIUtils networkMonitoring];
    if (stauts == 0) {
        [[AppDelegate app]viewHiddenWifiView];
    }
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isfrist"];
    [self viewWithWifiView];
    
    
    return YES;
}

- (void)AHReach
{
    //AHreach
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(struct sockaddr_in));
    addr.sin_len = sizeof(struct sockaddr_in);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(80);
    inet_aton("173.194.43.0", &addr.sin_addr);
    
    AHReach *addressReach = [AHReach reachForAddress:&addr];
    [addressReach startUpdatingWithBlock:^(AHReach *reach) {
        [self updateAvailabilityField:nil withReach:reach];
    }];
    [self updateAvailabilityField:nil withReach:addressReach];
    self.reaches = [NSArray arrayWithObjects:addressReach, nil];

}
#pragma mark - 实时判断网络状态
- (void)updateAvailabilityField:(UITextField *)field withReach:(AHReach *)reach {
    if([reach isReachableViaWWAN]) {
        MyNSLog("Available via WWAN");
        [self viewShowWifiView];
        [self WBSocket];

    } else if ([reach isReachableViaWiFi]) {
        MyNSLog("Available via WiFi");
       
        [self viewShowWifiView];
        
        [self WBSocket];
    }else{
        if (self.leftView) {
            
        }else{
            [self viewHiddenWifiView];
        }
    }
}
 - (void)ISChangeVersion
{
    NSString * postURL = @"https://itunes.apple.com/lookup?id=885697542";

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:postURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString * version = [[[responseObject objectForKey:@"results"] objectAtIndex:0] objectForKey:@"version"];
        if ([kVersion isEqualToString:version]){

        }else{
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}
#pragma - mark 微信
/**
 *  微信
 */
- (void)WXAlloc
{
    [WXApi registerApp:kWXAppKey withDescription:@"weixin"];
}
#pragma - mark WBSocket
/**
 *  初始化websocket
 */
- (void)WBSocket
{
    NSString * userIsLogin =  [NSString stringWithFormat:@"%@",[[UserManager shareInstance] getUserIsLogin]];
    if ([userIsLogin length] == 0 || [[UserManager shareInstance]getUserIsLogin] == nil) {
    }else{
        self.webSocket.delegate=nil;
        self.webSocket=nil;
        self.webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@:%@", HOST, PORT]]]];
        self.webSocket.delegate = self;
        [self.webSocket open];
    }
}
- (void)MaMap
{
    [MAMapServices sharedServices].apiKey = APIKey;
}
- (void)LeftAlloc
{
    /**
     初始化抽屉视图，MainViewController做主视图
     
     :returns: 无
     */
    self.drawerController = [[XHDrawerController alloc] init];
    self.drawerController.springAnimationOn = YES;
    LeftViewController *leftDrawerViewController = [[LeftViewController alloc] init];
    RightViewController *rightDrawerViewController = [[RightViewController alloc] init];
    MainViewController *centerSideDrawerViewController = [[MainViewController alloc] init];
    self.drawerController.leftViewController = leftDrawerViewController;
    self.drawerController.rightViewController = rightDrawerViewController;
    self.drawerController.centerViewController = centerSideDrawerViewController;
    if (![[NSUserDefaults standardUserDefaults]boolForKey:@"everLaunchView"]) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"everLaunchView"];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"MainViewController"];
        [[UIApplication sharedApplication] cancelAllLocalNotifications];
        [XGPush unRegisterDevice];
    }else{
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"MainViewController"];
        self.window.rootViewController = self.drawerController;
    }
    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"MainViewController"]) {
        LaunchView *launchView = [[LaunchView alloc]initWithFrame:self.window.frame];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"animation"];
        launchView.delegate = self;
        [self.window addSubview:launchView];
    }
}
- (void)launchViewDidFinish:(LaunchView *)launchView
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.4];
    launchView.alpha = 0;
    [UIView commitAnimations];
    [launchView performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:0.4];
    self.window.rootViewController = self.drawerController;
}
#pragma - marl sina登陆回调
/**
 *  Sina登陆完成
 *
 *  @param response 无
 */
- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    
    if ([response isKindOfClass:WBSendMessageToWeiboResponse.class])
    {
        if (response.statusCode==0) {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"Sina" object:self userInfo:nil];

        }else{

        }
    }
    else if ([response isKindOfClass:WBAuthorizeResponse.class])
    {
        
        self.wbtoken = [(WBAuthorizeResponse *)response accessToken];
        self.wbusid = [(WBAuthorizeResponse *)response userID];
        NSMutableDictionary *mDic = [NSMutableDictionary dictionary];
        if ([(WBAuthorizeResponse *)response userID] && ![[(WBAuthorizeResponse *)response userID] isEqualToString:@""]) {
            [mDic setObject:[(WBAuthorizeResponse *)response userID] forKey:@"uid"];
            NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
            [params setObject:[(WBAuthorizeResponse *)response userID] forKey:@"uid"];
            [WBHttpRequest requestWithAccessToken:self.wbtoken url:@"https://open.weibo.cn/2/users/show.json" httpMethod:@"GET" params:mDic delegate:self withTag:nil];
        }
    }

}
/**
 *  获得Sina的用户资料，通知传给登陆页面
 *
 *  @param request 无
 *  @param data    无
 */
- (void)request:(WBHttpRequest *)request didFinishLoadingWithDataResult:(NSData *)data
{
    self.sinaUserDictionry = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SinaLogin" object:self.sinaUserDictionry];

}
#pragma - mark 微信登录
/**
 *  授权后回调 WXApiDelegate
 *
 *  @param resp 无
 */
-(void)onResp:(BaseReq *)resp
{
    /*
     ErrCode ERR_OK = 0(用户同意)
     ERR_AUTH_DENIED = -4（用户拒绝授权）
     ERR_USER_CANCEL = -2（用户取消）
     code    用户换取access_token的code，仅在ErrCode为0时有效
     state   第三方程序发送时用来标识其请求的唯一性的标志，由第三方程序调用sendReq时传入，由微信终端回传，state字符串长度不能超过1K
     lang    微信客户端当前语言
     country 微信用户当前国家信息
     */
    
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp *aresp = (SendAuthResp *)resp;
        NSString *code = aresp.code;
        if ([code length ] != 0) {
                NSDictionary *dic = @{@"code":code};
                [[NSNotificationCenter defaultCenter] postNotificationName:@"WeixinLogin" object:dic];
            
            }
    }else if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        SendMessageToWXResp *messResp=(SendMessageToWXResp *)resp;

        if (messResp.errCode==0) {
            NSDictionary *dic=[[NSDictionary alloc]initWithObjectsAndKeys:resp,@"type", nil];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"WeChat" object:self userInfo:dic];
        }
    }
}

/**
 *  登陆回调
 *
 *  @param application       无
 *  @param url               无
 *  @param sourceApplication 无
 *  @param annotation        无
 *
 *  @return 无
 */
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    NSString * weiboOrQQstring = [NSString stringWithFormat:@"%@",url];
    weiboOrQQstring = [weiboOrQQstring substringToIndex:12];
    if ([weiboOrQQstring isEqualToString:@"wb2065981817"]) {
        return [WeiboSDK handleOpenURL:url delegate:self];
    }else if ([weiboOrQQstring isEqualToString:@"tencent10110"]){
        return [TencentOAuth HandleOpenURL:url];
    }else{
        return [WXApi handleOpenURL:url delegate:self];
    }
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    NSString * weiboOrQQstring = [NSString stringWithFormat:@"%@",url];
    weiboOrQQstring = [weiboOrQQstring substringToIndex:12];
    if ([weiboOrQQstring isEqualToString:@"wb2065981817"]) {
        return [WeiboSDK handleOpenURL:url delegate:self];
    }else if ([weiboOrQQstring isEqualToString:@"tencent10110"]){
        return [TencentOAuth HandleOpenURL:url];
    }else{
        return [WXApi handleOpenURL:url delegate:self];
    }
}

-(NSString*) uuid {
    CFUUIDRef puuid = CFUUIDCreate( nil );
    CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
    NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
    CFRelease(puuid);
    CFRelease(uuidString);
    return result;
}

#pragma mark
#pragma mark - SRWebSocketDelegate
- (void)webSocketDidOpen:(SRWebSocket *)webSocket;{
    /*
     srting action=login
     int uid 登录的uid
     string username 发送者名字
     string platform  设备信息 ios或者android
     type 发送者类型 发送者类型 1是用户  2是医生; 默认是1
     dateline 收到的最新的消息的时间（即收到的消息并且离现在最近的时间）；
     udid 唯一识别手机
     */

    MyNSLog("webSocket连接成功");
    if (!self.heartBeatTimer) {
        self.heartBeatTimer = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(heartBeat) userInfo:nil repeats:YES];
    }
    
    if (self.webSocket.readyState==1) {
        UserModel * userModel = [[UserManager shareInstance]getUserInfo];
        NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
        NSString * uid = userModel.uid;
        NSString * udidKey = [NSString stringWithFormat:@"udidkey%@",uid];
        if (![user objectForKey:udidKey]) {
            [user setObject:[self uuid] forKey:udidKey];
            self.udidString = [self uuid];
        }else{
            self.udidString = [user objectForKey:udidKey];
        }
        NSString *name=userModel.username;
        NSString *postString;
        NSString *receiveDateline = [ChatContent readTheLastDate];
        
        
        NSDictionary *loginDict = [[NSDictionary alloc] initWithObjectsAndKeys:@"login", @"action",uid, @"uid",name ,@"username",receiveDateline?:@"0",@"dateline", kPlatform, @"platform",@"1",@"type",self.udidString , @"udid", nil];
        MyNSLog("1==============%@", loginDict);
        postString = [loginDict JSONString];
        [self.webSocket send:postString];
    }
}
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error;{
    MyNSLog(":( Websocket Failed With Error %@", error);
    webSocket = nil;
}

- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean;{
    MyNSLog("WebSocket closed");
    webSocket = nil;
    if (!self.resignActive) {
        //webSocket closed 之后如果有网络就重新连接
        Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
        if ([r currentReachabilityStatus] == NotReachable) {
            MyNSLog("没有网络连接");
        } else {
            NSString * userIsLogin =  [NSString stringWithFormat:@"%@",[[UserManager shareInstance] getUserIsLogin]];
            if ([userIsLogin length] == 0 || [[UserManager shareInstance]getUserIsLogin] == nil) {
            }
            else
            {
                MyNSLog("有网络连接，重新连接websocket");
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"CONNECT_WEBSOCKDET" object:self userInfo:nil];
                [self WBSocket];

            }
        }
    }
}
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message
{
    MyNSLog("didReceiveMessage 聊天界面 = %@", message);
    MyNSLog("%@",message);
    
    
    
    if ([[YXJSON dictionaryOrArrayWithJSONSString:message] count]<=0) {
        return;
    }
    
    NSDictionary *dict = [YXJSON dictionaryOrArrayWithJSONSString:message];
    if ([[dict objectForKey:@"method"] integerValue] == 10) {
        [self otherLoginPrompt:message];
        return;
    }

    
    [self playMessageMusic];
    //在app中，收到消息，通过代理将消息发给对应页面
    if([[dict objectForKey:@"action"] isEqualToString:@"send"]) {
         [self sendReceiveActionWithReceiveDateline:[dict objectForKey:@"dateline"]];
        
        if (![self.chatDelegate isKindOfClass:[ConsultingChatViewController class]]) {
            LCStatusBarOverlay *statusbar=[LCStatusBarOverlay shared];
            [statusbar hidenMessageLabel];
            [statusbar analysisIMmessage:message];
            if ([[LCStatusBarOverlay shared] currentVC]) {
                
            }else{
                [statusbar showMessageLabel];

            }
        }
        if (self.chatDelegate) {
            //在在消息、对话、咨询列表页（list）、或者聊天页面
            if ([self.chatDelegate respondsToSelector:@selector(receiveMessage:Message:)]) {
                [self.chatDelegate receiveMessage:self Message:message];
            }
        }else
        {
            //在其他界面收到聊天消息，只进行存取数据（2个表）
            NSString *readStatus;
            if ([[dict objectForKey:@"type"] intValue] == 1) {
                NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                NSString *sqlPath=[docPath stringByAppendingPathComponent:@"mydatabase.sqlite"];
                FMDatabaseQueue * queue = [FMDatabaseQueue databaseQueueWithPath:sqlPath];
                dispatch_queue_t q1 = dispatch_queue_create("queue1", NULL);
                readStatus=@"1";

                //    dispatch_queue_t q2 = dispatch_queue_create("queue2", NULL);
                dispatch_async(q1, ^{
                    //加入耗时操作
                    NSDictionary *messageDic=[YXJSON dictionaryOrArrayWithJSONSString:message];
                    CGSize size;
                    if ([[messageDic valueForKey:@"pic"]length]>0) {
                        size=[ChatContent downloadImageSizeWithURL:[messageDic valueForKey:@"pic"]];
                        [messageDic setValue:[NSString stringWithFormat:@"%f",size.width] forKey:@"width"];
                        [messageDic setValue:[NSString stringWithFormat:@"%f",size.height] forKey:@"heigth"];
                        [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:messageDic] Andsuccess:@"1" AndMessageDirection:@"2"];
                    }
                    else{
                        [ChatContent insertChatMessageItem:message Andsuccess:@"1" AndMessageDirection:@"2"];
                    }
                    [PeerList updatePeerList:message withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"];
                    [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];
                });
            }else
            {
                readStatus=@"1";
                dispatch_queue_t queue = dispatch_get_main_queue();
                dispatch_async(queue, ^{
                    
                    
                    if ([ConsultList updateConsultList:message withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"]) {
                        NSString *meth=[NSString stringWithFormat:@"%@",[dict valueForKey:@"method"]];
                        if ([meth isEqualToString:@"9"]) {
                            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];
                            return ;
                        }
                    }
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //加入耗时操作
                        NSDictionary *messageDic=[YXJSON dictionaryOrArrayWithJSONSString:message];
                        CGSize size;
                        if ([[messageDic valueForKey:@"pic"]length]>0) {
                            size=[ChatContent downloadImageSizeWithURL:[messageDic valueForKey:@"pic"]];
                            [messageDic setValue:[NSString stringWithFormat:@"%f",size.width] forKey:@"width"];
                            [messageDic setValue:[NSString stringWithFormat:@"%f",size.height] forKey:@"heigth"];
                            [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:messageDic] Andsuccess:@"1" AndMessageDirection:@"2"];
                        }
                        else{
                            [ChatContent insertChatMessageItem:message Andsuccess:@"1" AndMessageDirection:@"2"];
                        }
                    });
                [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];
                });
            }
        }
    }
    //推送过来的聊天消息
    else
    {
        if (![self.chatDelegate isKindOfClass:[ConsultingChatViewController class]]) {
            LCStatusBarOverlay *statusbar=[LCStatusBarOverlay shared];
            NSArray * array1 = [[[dict objectForKey:@"history"] allKeys]sortedArrayUsingSelector:@selector(compare:)];
            for (int index=0; index<array1.count; index++) {
                NSString *keys=[array1 objectAtIndex:index];
                if([[[[dict objectForKey:@"history"] objectForKey:keys] objectForKey:@"action"] isEqualToString:@"send"])
                {
                    [statusbar hidenMessageLabel];
                    [statusbar analysisIMmessage:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]]];
                    if ([[LCStatusBarOverlay shared] currentVC]) {
                        
                    }else{
                        [statusbar showMessageLabel];
                        
                    }
                }
            }
        }
        if (self.chatDelegate) {
            //在在消息、对话、咨询列表页（list）、或者聊天页面
            if ([self.chatDelegate respondsToSelector:@selector(receiveRemoteNotificationMessage:Message:)]) {
                [self.chatDelegate receiveRemoteNotificationMessage:self Message:message];
            }
        }else
        {
            
            NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString *sqlPath=[docPath stringByAppendingPathComponent:@"mydatabase.sqlite"];
            FMDatabaseQueue * queue = [FMDatabaseQueue databaseQueueWithPath:sqlPath];
            dispatch_queue_t q1 = dispatch_queue_create("queue1", NULL);
            //    dispatch_queue_t q2 = dispatch_queue_create("queue2", NULL);
            dispatch_async(q1, ^{
                NSArray * array1 = [[[dict objectForKey:@"history"] allKeys]sortedArrayUsingSelector:@selector(compare:)];
                for (int index=0; index<array1.count; index++) {
                    NSString *keys=[array1 objectAtIndex:index];
                    if([[[[dict objectForKey:@"history"] objectForKey:keys] objectForKey:@"action"] isEqualToString:@"send"])
                    {
                        //在其他界面收到聊天消息，只进行存取数据（2个表）
                        NSString *readStatus;
                        if ([[[[dict objectForKey:@"history"] objectForKey:keys]  objectForKey:@"type"] intValue] == 1) {
                            readStatus=@"1";
                                    //加入耗时操作
                                    NSDictionary *messageDic=[[dict objectForKey:@"history"] objectForKey:keys];
                                    CGSize size;
                                    if ([[messageDic valueForKey:@"pic"]length]>0) {
                                        size=[ChatContent downloadImageSizeWithURL:[messageDic valueForKey:@"pic"]];
                                        [messageDic setValue:[NSString stringWithFormat:@"%f",size.width] forKey:@"width"];
                                        [messageDic setValue:[NSString stringWithFormat:@"%f",size.height] forKey:@"heigth"];
                                        [queue inDatabase:^(FMDatabase *db) {
                                            [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:messageDic] Andsuccess:@"1" AndMessageDirection:@"2"];
                                            [PeerList updatePeerList:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"];
                                        }];
                            }
                                    else{
                                        [queue inDatabase:^(FMDatabase *db) {
                                            
                                            [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] Andsuccess:@"1" AndMessageDirection:@"2"];
                                            [PeerList updatePeerList:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"];
                                        }];
                                    }
                            
                        }else
                        {
                            readStatus=@"1";
                            
                                    NSDictionary *messageDic=[[dict objectForKey:@"history"] objectForKey:keys];
                                    CGSize size;
                                    if ([[messageDic valueForKey:@"pic"]length]>0) {
                                        size=[ChatContent downloadImageSizeWithURL:[messageDic valueForKey:@"pic"]];
                                        [messageDic setValue:[NSString stringWithFormat:@"%f",size.width] forKey:@"width"];
                                        [messageDic setValue:[NSString stringWithFormat:@"%f",size.height] forKey:@"heigth"];
                                        [queue inDatabase:^(FMDatabase *db) {
                                            BOOL success=[ConsultList updateConsultList:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"];
                                            if (success) {
                                                NSString *meth=[NSString stringWithFormat:@"%@",[messageDic valueForKey:@"method"]];
                                                if ([meth isEqualToString:@"9"]) {
                                                    [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];
                                                    return ;
                                                }
                                            }
                                            [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:messageDic] Andsuccess:@"1" AndMessageDirection:@"2"];
                                        }];
                                        
                                    }
                                    else{
                                        [queue inDatabase:^(FMDatabase *db) {
                                            [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] Andsuccess:@"1" AndMessageDirection:@"2"];
                                            [ConsultList updateConsultList:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"];
                                        }];
                                        
                                }
                        }
                    }
                }
                [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];

            });
        }
    }
}
//收到消息之后发送当前的dateline
-(void)sendReceiveActionWithReceiveDateline:(NSString *)receiveDateline
{
    if (self.webSocket.readyState == 1) {
        UserModel * userModel = [[UserManager shareInstance]getUserInfo];
        NSString * uid = userModel.uid;
        NSDictionary *receiveDict = [NSDictionary dictionaryWithObjectsAndKeys:@"receive", @"action", [NSString stringWithFormat:@"%@", receiveDateline], @"dateline", uid, @"uid", @"2", @"type", nil];
        NSString *postString = [receiveDict JSONString];
        [self.webSocket send:postString];
    }
}
//* 连接到webSocket 时候发送本地最新的时间戳
-(void)sendLatestDateline
{
    UserModel * userModel = [[UserManager shareInstance]getUserInfo];
    NSString * uid = userModel.uid;
    NSString *receiveDateline = [ChatContent readTheLastDate];
    NSDictionary *receiveDict = [NSDictionary dictionaryWithObjectsAndKeys:@"receive", @"action", receiveDateline ? : @"0", @"dateline", uid, @"uid", @"1", @"type", nil];
    NSString *postString = [receiveDict JSONString];
    [self.webSocket send:postString];
}
-(void)otherLoginPrompt:(id)message
{
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"SelfUidKey"];

    //用户退出之后取消推送
    [XGPush unRegisterDevice];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];

    float tim=[[[YXJSON dictionaryOrArrayWithJSONSString:message] valueForKey:@"dateline"] doubleValue];
    NSString *tim1=[NSString stringWithFormat:@"%f",tim/10000 ];
    NSString *dateString = [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:tim1.floatValue]];
    
    NSString *mesTip=[NSString stringWithFormat:@"您的账号于%@在另一个设备上登录，如非本人操作则密码可能泄露",dateString];
    UIAlertView *confirmAlertView = [[UIAlertView alloc] initWithTitle:@"下线通知" message:mesTip delegate:self cancelButtonTitle:@"修改密码" otherButtonTitles:@"确定", nil];
    [confirmAlertView show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (self.leftView) {
        [self.drawerController closeDrawerAnimated:YES completion:^(BOOL finished) {
        }];
    }
    switch (buttonIndex) {
        case 0:
        {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"CrowdOut" object:nil];
            if (self.logoutDelegate &&[self.logoutDelegate respondsToSelector:@selector(logoutAndskiptoMain:)]) {
                [self.logoutDelegate logoutAndskiptoMain:@"0"];
            }
        }
            break;
        case 1:
        {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"CrowdOut" object:nil];
            
            if (self.logoutDelegate &&[self.logoutDelegate respondsToSelector:@selector(logoutAndskiptoMain:)]) {
                [self.logoutDelegate logoutAndskiptoMain:@"1"];
            }
        }
            //退出
        default:
            break;
    }
}
#pragma - mark APPDelegate
- (void)applicationWillResignActive:(UIApplication *)application
{

    [self.heartBeatTimer invalidate];
    self.heartBeatTimer = nil;
    self.resignActive = YES;
    [self.webSocket close];
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{

    
    [self.webSocket close];

    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    NSString * uid = [[UserManager shareInstance]getUserInfo].uid;
    NSString *pushmessAge = [NSString stringWithFormat:@"PushmessAge%@",uid];
    if ( [[user objectForKey:pushmessAge] length] != 0) {
        self.background =[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^(void) {
            [self loadWithData];
        }];
    }
    NSString * privacy = [NSString stringWithFormat:@"Privaty%@",uid];
    
    if ([[user objectForKey:privacy] length] != 0){
        self.background =[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^(void) {
            [self loadWithPriData];
        }];
    }
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{

    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{

    
    
    self.resignActive = NO;
    application.applicationIconBadgeNumber = 0;
    
    NSString * userIsLogin =  [NSString stringWithFormat:@"%@",[[UserManager shareInstance] getUserIsLogin]];
    
    if ([userIsLogin length] == 0 || [[UserManager shareInstance]getUserIsLogin ] == nil) {
        
    }
    else{

        [self WBSocket];
    }
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    NSString * uid = [[UserManager shareInstance]getUserInfo].uid;
    NSString *pushmessAge = [NSString stringWithFormat:@"PushmessAge%@",uid];
    NSString *pushmess= [NSString stringWithFormat:@"Pushmess%@",uid];
    [user removeObjectForKey:pushmessAge];
    [user setBool:NO forKey:pushmess];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"ios8"];

}
- (void)loadWithData
{
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    NSString * postURL = [NSString stringWithFormat:@"%@setting/message/",kBaseURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString * uid = [[UserManager shareInstance]getUserInfo].uid;
    NSString * pushNewKey = [NSString stringWithFormat:@"pushNew%@",uid];
    NSString * pushNew =[user objectForKey:pushNewKey];
    if ([pushNew length] == 0) {
        pushNew = @"1";
    }
    NSString * pushDetailKey = [NSString stringWithFormat:@"pushDetail%@",uid];
    NSString * pushDetail =[user objectForKey:pushDetailKey];
    if ([pushDetail length] == 0) {
        pushDetail = @"1";
    }
    NSString * pushActivityKey = [NSString stringWithFormat:@"pushActivity%@",uid];
    NSString * pushActivity =[user objectForKey:pushActivityKey];
    if ([pushActivity length] == 0) {
        pushActivity = @"0";
    }
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"2":@"people",@"remind":pushNew,@"showdetail":pushDetail,@"avoid":pushActivity};
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        MyNSLog("~~~~~    %@",responseObject);
        if ([statusString isEqualToString:@"1"]) {
            [[UIApplication sharedApplication] endBackgroundTask:self.background];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
    }];
    
}
- (void)loadWithPriData
{
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    NSString * postURL = [NSString stringWithFormat:@"%@user/lnglatsystem/",kBaseURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString * uid = [[UserManager shareInstance]getUserInfo].uid;
    NSString * pushNewKey = [NSString stringWithFormat:@"AllNear%@",uid];
    NSString * pushAnKey = [NSString stringWithFormat:@"AnNear%@",uid];
    NSString * pushDicKey = [NSString stringWithFormat:@"DoctionNear%@",uid];
    NSString * pushNew =[user objectForKey:pushNewKey];
    if ([[user objectForKey:pushNewKey] isEqualToString:@"3"] || [[user objectForKey:pushNewKey] length] == 0){
        if ([[user objectForKey:pushAnKey] isEqualToString:@"1"]&& [[user objectForKey:pushDicKey] isEqualToString:@"2"])
        {
            pushNew = @"3";
        }else if ([[user objectForKey:pushAnKey] isEqualToString:@"0"]&& [[user objectForKey:pushDicKey] isEqualToString:@"0"]){
            pushNew = @"4";
        }else if ([[user objectForKey:pushAnKey] length] == 0 && [[user objectForKey:pushDicKey] length]== 0){
            pushNew = @"2";
        }else if ([[user objectForKey:pushAnKey] length] == 0 && [[user objectForKey:pushDicKey] isEqualToString:@"2"]){
            pushNew = @"2";
        }else if ([[user objectForKey:pushAnKey] isEqualToString:@"0"] && [[user objectForKey:pushDicKey] isEqualToString:@"2"]){
            pushNew = @"2";
        }else if ([[user objectForKey:pushAnKey] isEqualToString:@"1"] && [[user objectForKey:pushDicKey] length]== 0){
            pushNew = @"1";
        }else if ([[user objectForKey:pushAnKey] isEqualToString:@"1"] && [[user objectForKey:pushDicKey] isEqualToString:@"0"]){
            pushNew = @"1";
        }else if ([[user objectForKey:pushAnKey] length] == 0 && [[user objectForKey:pushDicKey] isEqualToString:@"0"]){
            pushNew = @"1";
        }
    }else{
        pushNew = @"4";
    }
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"status":pushNew};
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"1"]) {
            NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
            NSString * uid = [[UserManager shareInstance]getUserInfo].uid;
            NSString * privacy = [NSString stringWithFormat:@"Privaty%@",uid];
            [user removeObjectForKey:privacy];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
    }];
    
}
#pragma - mark 信鸽
/**
 *  信鸽
 */
- (void)XGAlloc
{
    [[NSNotificationCenter defaultCenter] addObserverForName:@"loginTZ" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        
        if (IOS8_OR_LATER){
            [self registerPushForIOS8];
        }else{
            [self registerPush];
        }
    }];
    
    [XGPush startApp:2200004430 appKey:@"I63DBH31K9SN"];
    if (IOS8_OR_LATER){
        [self registerPushForIOS8];
    }else{
        [self registerPush];
    }
}
/**
 *  信鸽推送提示iOS7
 */
- (void)registerPush
{
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
}
/**
 *  信鸽推送提示iOS8
 */
- (void)registerPushForIOS8{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
    UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
    UIMutableUserNotificationAction *acceptAction = [[UIMutableUserNotificationAction alloc] init];
    acceptAction.identifier = @"ACCEPT_IDENTIFIER";
    acceptAction.title = @"Accept";
    acceptAction.activationMode = UIUserNotificationActivationModeForeground;
    acceptAction.destructive = NO;
    acceptAction.authenticationRequired = NO;
    UIMutableUserNotificationCategory *inviteCategory = [[UIMutableUserNotificationCategory alloc] init];
    inviteCategory.identifier = @"INVITE_CATEGORY";
    [inviteCategory setActions:@[acceptAction] forContext:UIUserNotificationActionContextDefault];
    [inviteCategory setActions:@[acceptAction] forContext:UIUserNotificationActionContextMinimal];
    NSSet *categories = [NSSet setWithObjects:inviteCategory, nil];
    UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:categories];
    [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
#endif
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    [XGPush localNotificationAtFrontEnd:notification userInfoKey:@"clockID" userInfoValue:@"myid"];
    [XGPush delLocalNotification:notification];
    
    //
    if (notification  && application.applicationState != UIApplicationStateActive) {
        
        NSString * string = [notification.userInfo objectForKey:@"userID"];
        
        if ([string isEqualToString:@"2"]) {
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"yongyao" object:nil];
            
            [[NSNotificationCenter defaultCenter] addObserverForName:@"yongyao1" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        
                TakeDrugReminderViewController * takeDrug = [[TakeDrugReminderViewController alloc] init];
                NSDictionary * familyInfoDic = [notification.userInfo objectForKey:@"FamilyInfoDic"];
                NSString * reminderTime =[notification.userInfo objectForKey:@"ReminderTime"];
                
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                [dateFormatter setDateFormat:@"HH:mm"];
                NSString * nowTime = [dateFormatter stringFromDate:[NSDate date]];
                if ([nowTime isEqualToString:reminderTime]) {
                    takeDrug.peopleDic = familyInfoDic;
                    takeDrug.isPresent = YES;
                    takeDrug.navBarTitle = @"用药提醒";
                    takeDrug.MedicalRecord = @"没有病历";
                    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:takeDrug];
                    nav.navigationBar.translucent = NO;
                    [nav setNavigationBarHidden:NO];
                    [UIApplication sharedApplication].statusBarHidden = NO;
                    [self.window.rootViewController presentViewController:nav animated:YES completion:nil];
                    return ;
                }
               
            }];
        }
    }
}
//
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    
    [[SystemMessageCenter instance] loadDataForIsFirstResign:NO];
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    self.tokenData = deviceToken;
}
- (void)loginSina
{
    [WeiboSDK enableDebugMode:YES];
    [WeiboSDK registerApp:kAppKey];
}
- (void)loginQQ
{
    NSString *appid = @"101101365";
    
    _tencentOAuth = [[TencentOAuth alloc] initWithAppId:appid
                                            andDelegate:self];
}
- (void)responseDidReceived:(APIResponse*)response forMessage:(NSString *)message
{
    
}

//- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag;
//{
//    // 播放结束时执行的动作
//    [self.player stop];
//    self.player.delegate = nil;
//    self.player = nil;
//}

- (void)viewWithWifiView
{
    self.wifiView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, 30)];
    self.wifiView.backgroundColor = [UIColor orangeColor];
    self.wifiView.alpha = 0;
    self.wifiView.tag = 1078;
    [[UIApplication sharedApplication].keyWindow  addSubview:self.wifiView];
    
    UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(kScreenWidth - 23, 6, 18, 18)];
    imageView.image = [UIImage imageNamed:@"closeWifi"];
    [self.wifiView addSubview:imageView];
    
    UITapGestureRecognizer * tap  = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(wifiHidden)];
    [self.wifiView addGestureRecognizer:tap];
    
    UILabel * wifiLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 5, 200, 20)];
    wifiLabel.text = @"暂时没有网络连接";
    wifiLabel.font = [UIFont systemFontOfSize:13];
    wifiLabel.textColor = [UIColor whiteColor];
    [self.wifiView addSubview:wifiLabel];
}
- (void)wifiHidden
{
    [UIView animateWithDuration:0.2 animations:^
     {
         self.wifiView.alpha = 0;
     } completion:^(BOOL finished)
     {
     }];
}
- (void)viewShowWifiView
{
    [UIView animateWithDuration:0.2 animations:^
     {
         self.wifiView.alpha = 0;
     } completion:^(BOOL finished)
     {
     }];
}
- (void)viewHiddenWifiView
{
    [UIView animateWithDuration:0.2 animations:^
     {
         self.wifiView.alpha = 1;
     } completion:^(BOOL finished)
     {
     }];
}
- (void)playMessageMusic
{
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    NSString * uid = [[UserManager shareInstance]getUserInfo].uid;
    NSString * soundKey = [NSString stringWithFormat:@"Sound%@",uid];
    NSString * playerUrl =[user valueForKey:soundKey];
    
    if (playerUrl.length<=0) {
        playerUrl=@"系统一";
    }
    
//    NSURL *url=[[NSURL alloc]initFileURLWithPath:[[NSBundle mainBundle] pathForResource:playerUrl ofType:@"mp3"]];
    
     [JSMessageSoundEffect playSoundWithName:playerUrl type:@"mp3"];
    
//    if (!self.player) {
//        self.player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
//    }
//    // 分配播放所需的资源，并将其加入内部播放队列
//    [self.player prepareToPlay];
//    // 播放
//    if ([self.player isPlaying]){
//        [self.player stop];
//    }else{
//        [self.player play];
//    }

}
-(void)heartBeat
{
    @try {
        if (self.webSocket.readyState == 1) {
            NSDictionary *heartBeatDict = [[NSDictionary alloc] initWithObjectsAndKeys:@"heartbeat", @"action", nil];
            NSString *postString = [heartBeatDict JSONString];
            [self.webSocket send:postString];
            MyNSLog("heartBeat");
        }
    }
    @catch (NSException *exception) {
        MyNSLog("exception = %@", exception);
    }
}


@end
